import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FileDialog;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import org.rosuda.JRI.RMainLoopCallbacks;
import org.rosuda.JRI.Rengine;

public class TextConsole extends JPanel implements RMainLoopCallbacks, ActionListener
{
	SweepViewGui sweepViewGui;
   	JPanel panel;
    public JTextArea textarea;
    public JTextField entry;
    
	public static Rengine re = null;
    public static ConsoleSync sync = new ConsoleSync();
 
    public TextConsole(SweepViewGui sweepViewGui) {
    	this.sweepViewGui = sweepViewGui;
    	panel = sweepViewGui.rConsolePanel;

    	textarea = sweepViewGui.rConsoleTextArea;
    	entry = sweepViewGui.RConsoleTextField;
	
    	entry.addActionListener(this);
    }

    public void rWriteConsole(Rengine re, String text, int oType) {
    	textarea.append(text);
    }
    
    public void rBusy(Rengine re, int which) {
       // System.out.println("rBusy("+which+")");
    }
    
    public String rReadConsole(Rengine re, String prompt, int addToHistory) {
        textarea.append(prompt);
        try {
        	String s = sync.waitForNotification();
        	textarea.append(s + "\n");
            //String s=entry.getText();
            return (s==null||s.length()==0)?s:s+"\n";
        } catch (Exception e) {
            System.out.println("jriReadConsole exception: "+e);
            e.printStackTrace();
        }
        return null;
    }
    
    public void rShowMessage(Rengine re, String message) {
        System.out.println("rShowMessage \""+message+"\"");
    }
    
    public String rChooseFile(Rengine re, int newFile) {
	FileDialog fd = new FileDialog((JFrame) sweepViewGui,
    	(newFile==0)?"Select a file":"Select a new file", (newFile==0)?FileDialog.LOAD:FileDialog.SAVE);
	fd.show();
	String res=null;
	if (fd.getDirectory()!=null) res=fd.getDirectory();
	if (fd.getFile()!=null) res=(res==null)?fd.getFile():(res+fd.getFile());
	return res;
    }
    
    public void   rFlushConsole (Rengine re) {
	}
    
    public void   rLoadHistory  (Rengine re, String filename) {
    }			
    
    public void   rSaveHistory  (Rengine re, String filename) {
    }

	public void actionPerformed(ActionEvent e) {
  		sync.triggerNotification(entry.getText());
  		entry.setText("");
//		REXP rexp = re.eval(entry.getText());
//		System.out.println(rexp);
//		System.out.println(rexp.getType());
//		System.out.println(rexp.rtype);
//		String[] output;
//		if (rexp.getType() !=  REXP.NILSXP)
//		{
//			output =rexp.asStringArray();
//			for(String line : output)
//			{
//				textarea.append(line+"\n");
//			}
//		}
//		textarea.append("----------------- Done ----------------\n");
//		entry.setText("");	
	}


}
